package com.opensky.qatest.ui.page;

import junit.framework.Assert;

import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.LoadableComponent;

import com.opensky.qatest.ui.component.JoinPageSignUpForm;
import com.opensky.qatest.util.common.AssertReport;
import com.opensky.qatest.util.common.LogicUtils;
import com.opensky.qatest.util.selenium.WebDriverWrapper;

/*
 * OpenSky - "Join page" model
 *
 * @author: Aliakse_Khursevich (hursevich@gmail.com)
 * @version: 1.0
 * 
 */
public class JoinPage extends LoadableComponent<JoinPage> implements IPage {

    // ************************ Locators ************************

    public static final String JOIN_PAGE_URL = "https://opensky.com/join";
    
    public static final String LOGO = "//img[@id='oslogo']";

    public static final String LOGO_LINK = "//div[@class='logo']//a";

    public static final String SIGNUP_FORM = "//div[@class='reg-form']/form";
    
    // ************************ Complex page objects **************************
    
    private JoinPageSignUpForm signUpForm;

    private final WebDriverWrapper driver;
    
    public JoinPage(WebDriverWrapper driver) {
	this.driver = driver;
	signUpForm = new JoinPageSignUpForm(driver);
    }

    // ************************ Actions **************************

    @Override
    protected void load() {
	driver.get(JOIN_PAGE_URL);
    }

    public HomePage clickLogo() {
	
	HomePage homePage = new HomePage(driver);
	
	driver.switchTo().defaultContent();
	driver.waitAndClick("LOGO_LINK", By.xpath(LOGO_LINK));
	
	if(homePage.isPageLoaded()) {
	    return homePage;
	} else {
	    return null;
	}
    }

    // ************************ Validations **************************

    @Override
    protected void isLoaded() throws Error {
	String url = driver.getCurrentUrl();
	Assert.assertTrue(AssertReport.wrongURL(JOIN_PAGE_URL, url), LogicUtils.isURLEqual(JOIN_PAGE_URL, url));
    }

    public boolean isPageLoaded() {
	return driver.waitAndCheckURL(JOIN_PAGE_URL);
    }
    
    public boolean isLogoPresent() {
	
	driver.waitAndCheckElementPresent("LOGO", By.xpath(LOGO));
	return true;
    }

    // ************************ GET/SET methods **************************
    
    public JoinPageSignUpForm getSignUpForm() {
	
	if(driver.waitAndVerifyElementPresent(By.xpath(SIGNUP_FORM))) {
	    return signUpForm;
	} else {
	    return null;
	}
	
    }

}
